import os
import sys
import ctypes
import signal
from functools import partial
from PySide2.QtWidgets import QApplication

from multiprocessing import Manager, freeze_support
from gglobal import logger

# 本地模块导入
from gglobal.process_manager import ProcessManager
from mooetoolapp.views.appshow import AppShow


class Application(QApplication):
    def __init__(self, argv):
        super().__init__(argv)


def run_application() -> None: # Removed shared_config argument
    """GUI 主应用进程"""
    try:
        # 指定 VisPy 使用 PySide2 后端，避免打包后后端探测失败
        os.environ.setdefault("VISPY_BACKEND", "pyside2")
        if sys.platform == "win32":
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("mooetool")


        app = Application(sys.argv)
        app_show = AppShow()
        win = app_show.initialize()
        app_show.show()

        # 应用退出时终止所有进程
        app.aboutToQuit.connect(lambda: (
            logger.info("[App] 应用程序退出信号接收"),
            sys.exit(0)
        ))

        ret = app.exec_()
        logger.info("[App] 应用程序退出码: %s", ret)
    except Exception as e:
        logger.exception("[App] 应用程序异常: %s", e)
    finally:
        sys.exit(0)


def run_as_admin() -> bool:
    """跨平台管理员权限检查"""
    try:
        if sys.platform == "win32":
            if ctypes.windll.shell32.IsUserAnAdmin():
                return True
            # Windows 提权逻辑
            ctypes.windll.shell32.ShellExecuteW(
                None, "runas", sys.executable, " ".join(sys.argv), None, 1
            )
            return False
        else:
            # Linux/macOS 需要其他处理方式
            return os.getuid() == 0
    except Exception as e:
        logger.error("[Init] 权限检查失败: %s", e)
        return False


def main() -> None:
    """主程序入口"""
    try:
        # 信号处理
        def signal_handler(signum, frame):
            if signum == signal.SIGINT:
                logger.info("[Signal] 收到 SIGINT 信号")
            elif signum == signal.SIGTERM:
                logger.info("[Signal] 收到 SIGTERM 信号")
            manager.terminate_all()

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)

        with Manager() as shared_manager:
            shared_config = shared_manager.dict()
            manager = ProcessManager()

            # 记录系统进程信息
            manager.add_system_processes()  # 新增调用
            shared_config["RootPID"] = manager.root_pid
            shared_config["MainPID"] = manager.main_pid

            # 添加进程（使用 partial 传参）
            # manager.add_process("Application", partial(run_application, shared_config))
            manager.add_process("Application", partial(run_application))

            # 启动进程
            manager.start_process("Application")
            manager.list_processes()
            manager.print_process_tree()

            # 等待主进程退出
            manager.processes["Application"].join()
            logger.info("[Main] 主进程已结束，正在清理...")

    except KeyboardInterrupt:
        logger.info("[Main] 收到键盘中断信号")
    except Exception as e:
        logger.exception("[Main] 主程序异常: %s", e)
    finally:
        manager.terminate_all()
        logger.info("[Main] 系统退出")

        # 增加主进程自终止逻辑
        if os.getpid() == manager.main_pid:
            logger.info("主控制进程自行退出")
            os._exit(0)


if __name__ == "__main__":
    freeze_support()
    if not run_as_admin():
        sys.exit(1)
    main()
